<?php
/**
 * Created by PhpStorm.
 * User: tongwei
 * Date: 2018/11/2
 * Time: 6:04 PM
 */

namespace App\Http\Controllers\Front;


use App\Http\Controllers\Controller;
use App\Model\Common;
use Illuminate\Http\Request;

class OssController extends Controller
{
	/**
	 * oss web直传
	 */
	public function getWebPolicy()
	{

		$id=env('AliyunAccessKeyId');          // AccessKeyId。
		$key= env('AliyunAccessKeySecret');     // AccessKeySecret。
		$host = 'http://hytx-upload-images.oss-cn-beijing.aliyuncs.com';
		$callbackUrl = env('apiUrl'); //'http://www.51huimaibao.cn';
		$dir = 'hytx/images/'.date('ymd').'/';          // 用户上传文件时指定的前缀。

		$callback_param = array('callbackUrl'=>$callbackUrl,
			'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
			'callbackBodyType'=>"application/x-www-form-urlencoded");
		$callback_string = json_encode($callback_param);

		$base64_callback_body = base64_encode($callback_string);
		$now = time();
		$expire = 30;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
		$end = $now + $expire;
		$expiration =  $this->gmt_iso8601($end);

		//最大文件大小.用户可以自己设置5242880b=5mb
		$condition = array(0=>'content-length-range', 1=>0, 2=>5242880);
		$conditions[] = $condition;

		// 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
		$start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
		$conditions[] = $start;

		$arr = array('expiration'=>$expiration,'conditions'=>$conditions);
		$policy = json_encode($arr);
		$base64_policy = base64_encode($policy);
		$string_to_sign = $base64_policy;
		$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

		$response = array();
		$response['accessid'] = $id;
		$response['host'] = $host;
		$response['policy'] = $base64_policy;
		$response['signature'] = $signature;
		$response['expire'] = $end;
		$response['callback'] = $base64_callback_body;
		$response['dir'] = $dir;  // 这个参数是设置用户上传文件时指定的前缀。
        echo json_encode($response);exit;
		return $this->renderJson($response);
	}

	private function gmt_iso8601($time) {
		$dtStr = date("c", $time);
		$mydatetime = new \DateTime($dtStr);
		$expiration = $mydatetime->format(\DateTime::ISO8601);
		$pos = strpos($expiration, '+');
		$expiration = substr($expiration, 0, $pos);
		return $expiration."Z";
	}

    public function aliyunImgBase(Request $request)
    {
//        $path = "http://thirdwx.qlogo.cn/mmopen/vi_32/Uz0EHlJnP5BCCR6LsScX3KoIiatBAVjLT8R2DiaUIFqcwGU7ibiaTENa208hImwVlPZISX8NkyPStHYWLoD2YYr6ng/132";
        $path = $request->get ("path");
        $url = Common::curl_file_get_contents ($path);

        $imgName = \Illuminate\Support\Str::random(16) . time() . '.jpg';
        $imgPath = base_path('public') . '/' . $imgName;
        file_put_contents ($imgPath, $url);
        $re = $this->imgToBase64($imgPath);
        unlink(public_path($imgName));
        return $re;
    }

    private function imgToBase64($img_file) {
        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
            }
            fclose($fp);
        }
        return $img_base64; //返回图片的base64
    }
}